<template>
  <div>
    <!-- 搜索结果组件 -->
    <van-cell title="搜索结果">
      <template #right-icon>
        <van-icon name="close" />
      </template>
    </van-cell>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell v-for="item in resultsList" :key="item.art_id" :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/article'
export default {
  props: {
    searchText: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      resultsList: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 30,
      error: false
    }
  },
  methods: {
    async onLoad() {
      // 搜索文章
      try {
        const { data: res } = await getSearchResults({
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.searchText // 搜索关键字
        })
        this.resultsList.push(...res.data.results)
        // 加载状态结束
        this.loading = false

        // 判断是否加载结束
        if (res.data.results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
        this.error = true
      }
    }
  }
}
</script>

<style lang='less' scoped>
</style>
